<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        arr = [
            { id: "29", pid: '', name: '总裁办' },
            { id: "2c", pid: '', name: '财务部' },
            { id: "2d", pid: '2c', name: '财务核算部' },
            { id: "2f", pid: '2c', name: '薪资管理部' },
            { id: "d2", pid: '', name: '技术部' },
            { id: "d3", pid: 'd2', name: 'java研发部' }
        ]

        function tranListToTreeData(list) {
            const treeList = [], map = {}

            //给每个对象添加children数组
            list.forEach(item => {
                if (!item.children) {
                    item.children = []
                }

                //把数组里的id作为对象名 
                map[item.id] = item
                console.log(map);
            })
            /*
            map = {
                29 : { id: "29", pid: '', name: '总裁办' },
                2c : { id: "2c", pid: '', name: '财务部' },
                2d : { id: "2d", pid: '2c', name: '财务核算部' },
                2f : { id: "2f", pid: '2c', name: '薪资管理部' },
                d2 : { id: "d2", pid: '', name: '技术部' },
                d3 : { id: "d3", pid: 'd2', name: 'java研发部' }
                    }
            */
            list.forEach(item => {
                const parent = map[item.pid]

                if (parent) {
                    parent.children.push(item)
                } else {
                    treeList.push(item)
                }
            })

            return treeList
           
        }

        const newArr = tranListToTreeData(arr)
        // console.log(newArr);
    </script>
</body>

</html>